<template>
  <el-row>
    <el-col :span="1">
      <div class="grid-content bg-purple-light">
        <!-- <div style="height: 50px;"></div> -->
        <!-- <div style="background-color: #ccc;height: 500px; width: 6px;margin-left:43px;"></div> -->
      </div>
    </el-col>
    <el-col :span="15">
      <div style="margin-bottom: 0px; background-color:#ccc;height:40px;">
        <div style="padding-top: 8px;font-size: 20px;">远程文件浏览器</div>
      </div>
      <el-row>
        <el-col :span="1">
          <div>
            <div style="background-color: #ccc;height: 578px; width: 6px;"></div>
          </div>
        </el-col>
        <el-col :span="23">
          <div>
            <el-row>
              <el-col :span="2"><div style="margin-top: 10px;" class="grid-content bg-purple">
                <el-button icon="el-icon-back" @click="getBack" class="btn1Class" circle></el-button>
              </div></el-col>
              <el-col :span="9"><div style="margin-top: 10px;" class="grid-content bg-purple-light">
                <el-input v-model="selectpath"  class="filter-item" placeholder="请输入路径"
                          @keydown.enter.native="selectFiles" ></el-input>
              </div></el-col>
              <el-col :span="2"><div style="margin-top: 10px;" class="grid-content bg-purple">
                <el-button icon="el-icon-search" @click="selectFiles" class="btn2Class" circle></el-button>
              </div></el-col>
              <el-col :span="9"><div style="margin-top: 10px;" class="grid-content bg-purple-light">
                <el-input v-model="selectname" class="filter-item" placeholder="请输入名称"
                          @keydown.enter.native="selectName"></el-input>
              </div></el-col>
              <el-col :span="2">
                <div style="margin-top: 10px;" class="grid-content bg-purple">
                  <el-button icon="el-icon-search" @click="selectName" class="btn2Class" circle></el-button>
              </div></el-col>
            </el-row>
              <div class="explorerBox">
                <jason-vue-explorer
                v-loading="loading"
                mode="normal"
                v-if="FiledataArr.length>0"
                :data-arr="FiledataArr"
                :selected-arr.sync="selectedArr"
                @clickFolder="clickFolder"
                @clickFile="clickFile"
                @dblclickFolder="dblclickFolder"
                @dblclickFile="dblclickFile"/>
              </div>
              <!-- <div style="background-color: #ccc;height: 10px;"></div> -->
              <div style="height: 40px; text-align: right;">

                <el-button v-show="!selectAllAddr.includes(selectpath)||TaskdataArr.length==0" style="margin-right: 10px;" class= "btn3Class" @click= "selectAll()" round >全选</el-button>
                <el-button v-show="selectAllAddr.includes(selectpath)" style="margin-right: 10px;" class= "btn3Class" @click= "removeAll()" round >取消全选</el-button>
                <el-button style="margin-right: 10px;" class= "btn3Class" @click= "submitList" round >加入提交列表</el-button>
                <el-button class= "btn3Class"  @click = "reChoose" :disabled="TaskdataArr.length===0" round>重置选择列表</el-button>
              </div>
              <!-- <div style="background-color: #ccc;height: 10px;"></div> -->
            </div>
          <!-- <div style="margin-bottom: 0px; background-color:#ccc ;"></ -->
        </el-col>

      </el-row>

    </el-col>
    <el-col :span="1">
      <div class="grid-content bg-purple-light">
        <div style="background-color: #ccc;height: 600px; width: 6px;"></div>
      </div>
    </el-col>
    <el-col :span="8">
      <div class="grid-content bg-purple">
        <div style="margin-bottom: 0px; background-color:#ccc;height:40px;">
          <div style="padding-top: 8px;font-size: 20px;">已选中</div>
        </div>
        <el-row>
          <el-col :span="1">
            <div class="grid-content bg-purple">
              <div style="margin-top: 0px;" class="grid-content bg-purple-light">
                <div style="background-color: #ccc;height: 578px; width: 6px;"></div>
              </div>
            </div></el-col>
          <el-col :span="23">
            <div class="grid-content bg-purple-light">
              <div class="explorerBox">
                <jason-vue-explorer
                mode="normal"
                :data-arr="TaskdataArr"
                :selected-arr.sync="TaskSelectedArr"
                @clickFolder="clickFolder"
                @clickFile="clickFile"
                @dblclickFolder="dblclickFolder"
                @dblclickFile="dblclickFile"/>
              </div>
              <div style="height: 40px; text-align: right;margin-top: 40px;">
<!--                <el-button class="btn3Class" round :disabled="true">文件夹数量: {{this.fileDirCount}}</el-button>-->
<!--                <el-button class="btn3Class" round :disabled="true">文件数量: {{this.fileCount}}</el-button>-->
                <el-button type="primary" class="btn3Class" round :disabled="true" v-loading="isSelectAllLoading"><b>文件夹数量: {{this.fileDirCount}}</b></el-button>
                <el-button type="primary" class="btn3Class" round :disabled="true " v-loading="isSelectAllLoading"><b>文件数量: {{this.fileCount}}</b></el-button>
                <el-button style="margin-right: 10px;" class= "btn3Class" @click= "removefilelist" :disabled="TaskdataArr.length===0||TaskSelectedArr.length===0" round >移除</el-button>
                <el-button class= "btn3Class"  @click = "reChoose" :disabled="TaskdataArr.length===0" round>重置选择列表</el-button>
                <el-button class= "btn3Class"  @click = "submitsnip"  :disabled="getsubmitstatus()" round>提交任务</el-button>
                <el-dialog
                title="提示"
                :append-to-body="true"
                :close-on-click-modal="false"
                :visible.sync="snipDialogVisible"
                width="30%"
                center>
                <span>本次提交任务与上次相同是否重复提交</span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="snipDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="snipClick">确 定</el-button>
                </span>

                </el-dialog>
                <el-dialog
                title="提交识别任务"
                :append-to-body="true"
                :close-on-click-modal="false"
                :visible.sync="centerDialogVisible"
                width="30%"
                @close = "cancel"
                center>
                <el-form ref="form" :model="form" :rules="rules" size="small" label-width="160px">
                  <el-form-item label="任务名称" >
                    <el-input v-model="form.taskname" placeholder = "请输入任务名称" style="max-width: 250px;"/>
                  </el-form-item>
<!--                  <el-form-item label="权重" >-->
<!--                    <el-input type = "number" v-model="form.weight" placeholder = "权重越大越优先" style="max-width: 250px;"  />-->
<!--                  </el-form-item>-->
                  <el-form-item label="识别方式">
                    <el-radio-group v-model="form.ignore">
                      <el-radio label="ignore" >忽略已识别过的</el-radio>
                      <el-radio label="all" >强制更新</el-radio>
                    </el-radio-group>
                  </el-form-item>
<!--                  <el-form-item label="是否插队">-->
<!--                    <el-radio-group v-model="form.insert">-->
<!--                      <el-radio label="false" >否</el-radio>-->
<!--                      <el-radio label="true" >是</el-radio>-->
<!--                    </el-radio-group>-->
<!--                  </el-form-item>-->
                  <el-form-item label="是否进行数字识别">
                    <el-radio-group v-model="form.is_num_ocr">
                      <el-radio label="0">否</el-radio>
                      <el-radio label="1">是</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="是否生成识别结果图片">
                    <el-radio-group v-model="form.generate">
                      <el-radio label="0" >否</el-radio>
                      <el-radio label="1" >是</el-radio>
                    </el-radio-group>
                  </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="cancel">取 消</el-button>
                  <!--form.weight ==='' ||-->
                  <el-button type="primary" @click="submitTask" :disabled="  form.taskname === '' ">确 定</el-button>
                </div>
              </el-dialog>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-col>
  </el-row>
</template>

<script>
// import {getFiles,submitTaskApi,insertTaskApi,getTaskImageNum, searchFileByName} from '../service/commonService'
import {submitTask, getJsonList, searchFileByName, getTaskImageNum} from '../service/common'
import jasonVueExplorer from './explorer'
export default {
  name: 'Taskchoose',
  props: {
    fileList: {}
  },
  components: {
    jasonVueExplorer,
  },
  data () {
    return {
      isSelectAllLoading: false,
      selectAllAddr: [],
      loading: false,
      // 已选中json数量
      fileCount: 0,
      fileDirCount: 0,

      assignImageNum: 0,
      saveSearchData: [], // 搜索后的数组
      submitstatus:true,
      snipDialogVisible:false,
      form:{
        taskname:'',
        weight:'',
        ignore:'ignore',
        insert:'false',
        generate:'1',
        is_num_ocr: '0'
      },
      rules: {
      },
      selectname:'',
      url: '',
      srcList: [],
      imageUrl: '',
      actionUrl: '',
      imageUrlable: '',
      is: false,
      centerDialogVisible: false,
      selectpath:'',
      currentPath: '',
      pathStack: [],
      FiledataArr: [],  // 文件列表
      dataCopy:[],  // 当前路径下的列表
      TaskdataArr:[],
      selection: true,
      selectedArr: [],
      TaskSelectedArr:[],
      submitdataArr:[],
      otherColumnArr: [
        {
          label: '时间',
          key: 'time'
        }
      ],
      seletedFileList: [],
    }
  },
  created () {
    this.selectpath = process.env.VUE_APP_SELECT_PATH
    this.getResource()
  },
  methods: {
    snipClick(){
      this.snipDialogVisible = false
      this.centerDialogVisible = true
    },
    submitsnip(){
      // console.log('this.TaskdataArr',this.TaskdataArr)
      // console.log('this.submitdataArr',this.submitdataArr)
      // console.log(this.TaskdataArr === this.submitdataArr)
      if(this.TaskdataArr === this.submitdataArr)
      {
        this.snipDialogVisible = true
      }
      else{
        this.centerDialogVisible = true
      }
    },
    getsubmitstatus(){
      if(this.TaskdataArr.length ===  0)
      {
        return true
      }
      // else if(this.submitstatus === false)
      // {
      //   return true
      // }
      return false
    },
    cancel() {
      this.resetForm()
    },
    resetForm() {
      this.centerDialogVisible = false
      this.$refs['form'].resetFields()
      this.form = {
        taskname:'',
        weight:'',
        ignore:'ignore',
        insert:'false',
        generate:'1',
        is_num_ocr: '0'
      }
    },
    selectName() {
      this.saveSearchData = []
      if (this.selectname === "") {
        this.getResource()
      } else {
        this.loading = true
        //  根据路径和搜索词搜索文件
        searchFileByName(this.selectpath, this.selectname, 'json').then(res => {
          this.FiledataArr = []
          let file_result = res.data.file_result
          let dir_result = res.data.dir_result
          let key = Date.parse(new Date());
          // 将文件放进
          for (let data of file_result) {
            let data_item = {}
            data_item['key'] = key++
            data_item['name'] = data.filename
            data_item['filepath'] = data.root + '/' + data.filename
            data_item['type'] = 'json'
            data_item['isSearch'] = true
            // if (item.type === 'image') {
            //   data_item['height'] = item.height
            //   data_item['size'] = item.size
            //   data_item['width'] = item.width
            // }
            this.FiledataArr.push(data_item)
          }
          // 将文件夹放入
          for (let data of dir_result) {
            let data_item = {}
            data_item['key'] = key++
            data_item['name'] = data.dirname
            data_item['filepath'] = data.root + '/' + data.dirname
            data_item['type'] = 'folder'
            data_item['isSearch'] = true
            this.FiledataArr.push(data_item)
          }
          this.loading = false
          console.log("FiledataArr", this.FiledataArr)
        })
      }
    },
    // 根据搜索词递归查找文件函数
    searchData(data) {
      for(let i=0;i<data.length;i++){
        if(!data[i].name.indexOf(this.selectname)){
          console.log("保存了",data[i].name)
          this.saveSearchData.push(data[i])
          // console.log("this.saveSearchData",this.saveSearchData)
        }
        if(data[i].type == "folder"){
          // console.log("进文件夹了",data[i].name)
          let key = Date.parse(new Date());
          let folderDataList = []
          // getFiles(data[i].filepath).then((res) => {
          getJsonList(data[i].filepath).then((res) => {
            // console.log("98888888888888888888888888888",res)
            if (res.data.status === 1) {
              let folderFiles = res.data.allList
              console.log("文件夹"+data[i].name+"下有:",folderFiles)
              if(folderFiles.length != 0)
              for (let item of folderFiles) {
                let data_item = {}
                data_item['key'] = key++
                data_item['name'] = item.filename
                data_item['filepath'] = item.filepath
                data_item['type'] = item.type
                if (item.type === 'image') {
                  data_item['height'] = item.height
                  data_item['size'] = item.size
                  data_item['width'] = item.width
                }
                folderDataList.push(data_item)
              }
              if(folderDataList.length != 0){
                console.log(data[i].name+"的的的新一轮的遍历")
                this.searchData(folderDataList)
              }
            }
          }).catch((error) => {
            // console.log('fileSel与后端通讯发生错误', error)
          })
        }
      }
    },
    getResource() {
      this.getData(this.selectpath)
    },
    getData(filepath) {
      let i = Date.parse(new Date());
      // getFiles(filepath).then((res) => {
      getJsonList(filepath).then((res) => {
        // console.log('返回成功，结果：', res)
        if (res.data.status === 1) {
          this.FiledataArr = []
          let folderFiles = res.data.allList
          for (let item of folderFiles) {
            // // console.log(item)
            let data_item = {}
            data_item['key'] = i++
            data_item['name'] = item.filename
            data_item['filepath'] = item.filepath
            data_item['type'] = item.type
            if (item.type === 'image') {
              data_item['height'] = item.height
              data_item['size'] = item.size
              data_item['width'] = item.width
              // data_item['base64'] = item.base64
            }
            this.FiledataArr.push(data_item)
          }
          this.dataCopy = this.FiledataArr
          console.log("dataCopy里有",this.dataCopy)
          this.currentPath = filepath // 获取filepath下的文件夹后，把当前路径设置为filepath
          this.selectpath = filepath
          this.seletedFileList=[]
          this.selectedArr=[]
        } else {
          this.openMessageBox('路径不存在')
        }

      }).catch((error) => {
        // console.log('fileSel与后端通讯发生错误', error)
      })
    },
    submitSuccessNotify(msg) {
      this.$notify({
        title: msg ,
        type: 'success',
        duration: 2500
      })
    },
    submitFailureNotify(msg,error) {
      this.$notify({
        title: msg + error,
        type: 'error',
        duration: 2500
      })
    },
    clickFolder(item) {
      // console.log('clickFolder', item)
    },
    clickFile(item) {
      // console.log('clickFile', item)
    },
    dblclickFolder(event) {
      // console.log('双击文件夹，进入别的文件夹，需要将当前路径记录在栈里')
      this.pathStack.push(this.currentPath)
      const folderPath = event['filepath']
      // console.log('pathStack:', this.pathStack)
      this.explorerInit()
      console.log('selectedFileList1',this.seletedFileList)
      if (event['type'] === 'folder') {
      this.getData(folderPath)
      }
    },
    dblclickFile() {
      // console.log('dblclickFile')
    },
    selectFiles() {
      this.getData(this.selectpath)
      this.pathStack.push(this.currentPath)
    },
    getBack() {
      // console.log('返回上一级')
      const i = this.pathStack.length
      if (i >= 1) {
        this.explorerInit()
        const backPath = this.pathStack[i - 1] // 取栈顶元素
        this.pathStack.pop()
        // console.log('返回上一级路径', backPath)
        this.getData(backPath)
      } else {
        this.openMessageBox('没有上一级了！')
      }
    },
    openMessageBox(message) {
      this.$alert(message, ' ', {
        confirmButtonText: '确定'
        // callback: action => {
        //   this.$message({
        //     type: 'info',
        //     message: `action: ${ action }`
        //   });
        // }
      })
    },
    dragMove(folder, data) {
      // console.log(folder, data)
    },
    explorerInit() {
      this.selectedArr.splice(0, this.selectedArr.length)
      console.log('init',this.selectedArr)
      this.FiledataArr.splice(0, this.FiledataArr.length)
      this.selection = true
      this.seletedFileList.splice(0, this.seletedFileList.length)
    },
    // 取消全选
    removeAll(){
      let flag = false
      if(this.selectAllAddr.includes(this.selectpath)){
        console.log(this.selectAllAddr)
        for(let i = 0; i < this.selectAllAddr.length; i++){
          if(this.selectAllAddr[i] == this.selectpath){
            this.selectAllAddr.splice(i,1);
            flag = true
            console.log(this.selectAllAddr)
            break;
          }
        }
      // 如果包含该路径
        if(flag){
          let json = this.selectedArr.concat(this.TaskdataArr)
          let newJson = []; // 用来存最终选定结果
          for (let i = 0; i < json.length; i++) {
            for (let j = 0; j < this.FiledataArr.length; j++) {
              if (this.FiledataArr[j].filepath == json[i].filepath) {
                newJson.push(this.FiledataArr[j]);
                continue;
              }
            }
          }
          this.isSelectAllLoading = true
          // 获取数量
          getTaskImageNum(newJson,'json').then(res=>{
            this.fileCount -= res.data.fileCount
            this.fileDirCount -= res.data.fileDirCount
            this.isSelectAllLoading = false
          })
          for(let i = 0; i < this.FiledataArr.length; i++){
            for(let j = 0; j < json.length; j++){
              if(json[j].filepath == this.FiledataArr[i].filepath){
                json.splice(j,1);
                j=j-1;
              }
            }
          }
          this.TaskdataArr = json
          this.selectedArr = []
        }
      }
    },
    // 全选
    selectAll() {
      this.selectAllAddr.push(this.selectpath);
      let json = this.selectedArr.concat(this.TaskdataArr)
      json = json.concat(this.FiledataArr)
      let newJson = []; // 用来存最终选定结果
      for (let i = 0; i < json.length; i++) {
        let flag = false;
        for (let j = 0; j < newJson.length; j++) {
          if (newJson[j].filepath == json[i].filepath) {
            flag = true;
          }
        }
        if (!flag) { //判断是否重复    若不重复则加入
          newJson.push(json[i]);
        }
      }
      this.isSelectAllLoading = true
      // 获取数量
      getTaskImageNum(newJson,'json').then(res=>{
        this.fileCount = res.data.fileCount
        this.fileDirCount = res.data.fileDirCount
        this.isSelectAllLoading = false
      })
      this.TaskdataArr = newJson
      this.selectedArr = []
    },
    // 加入提交列表
    submitList(){
      let json = this.selectedArr.concat(this.TaskdataArr)
      let newJson = []; // 用来存最终选定结果
      for(let i = 0;i < json.length;i++){
        let flag = false;
        for(let j=0;j < newJson.length;j++){
            if(newJson[j].filepath==json[i].filepath){
                flag = true;
            }
        }
        if(!flag){ //判断是否重复    若不重复则加入
            newJson.push(json[i]);
        }
      }
      // 获取数量
      getTaskImageNum(newJson,'json').then(res=>{
        this.fileCount = res.data.fileCount
        this.fileDirCount = res.data.fileDirCount
      })
      this.TaskdataArr = newJson
      this.selectedArr = []
    },
    reChoose(){
      this.fileCount = 0
      this.fileDirCount = 0
      this.selectedArr = []
      this.TaskdataArr = []
      this.TaskSelectedArr = []
    },
    removefilelist(){
      let list = []
      for(let i=0 ;i<this.TaskdataArr.length ;i++)
      {
        if(this.TaskSelectedArr.indexOf(this.TaskdataArr[i]) === -1){
          list.push(this.TaskdataArr[i])
        }
      }
      // 移除后重新获取数量
      this.fileCount = 0
      this.fileDirCount = 0
      getTaskImageNum(list,'json').then(res=>{
        this.fileCount = res.data.fileCount
        this.fileDirCount = res.data.fileDirCount
      })
      this.TaskdataArr = list
      this.TaskSelectedArr = []
    },
    submitTask() {
      if(this.form.weight == ""){
        let jsonNum = this.TaskdataArr.length
        if(jsonNum < 6){
          this.form.weight = 800
        }else if(jsonNum < 11){
          this.form.weight = 500
        }else if(jsonNum < 51){
          this.form.weight = 200
        }else {
          this.form.weight = 1
        }
      }
      this.centerDialogVisible = false
      this.submitdataArr = this.TaskdataArr
      // let i = Date.parse(new Date());
      let jsonList = []
      for(let i=0;i<this.TaskdataArr.length;i++)
      {
        let one=[]
        one.push(this.TaskdataArr[i].type)
        one.push(this.TaskdataArr[i].filepath)
        jsonList.push(one)
      }
      this.submitstatus =  false
      if(this.form.insert === "false")
      {

        // submitTaskApi(this.form.taskname,this.form.weight, this.form.ignore, jsonList,this.form.generate).then((res) => {
        submitTask(this.form.taskname,this.form.weight, this.form.ignore, jsonList,this.form.generate,this.form.is_num_ocr).then((res) => {
        // console.log('返回成功，结果：', res)
        if (res.status === '1') {
          this.submitSuccessNotify('提交任务成功')
          this.submitstatus =  true
        } else {
          this.submitFailureNotify('提交任务失败','')
          this.submitstatus =  true
          // console.log('11111111', this.dataArr)
        }
        }).catch((error) => {
          this.submitFailureNotify('fileSel与后端通讯发生错误', error)
          this.submitstatus =  true
        })
      }
      else{
        insertTaskApi(this.form.taskname,this.form.weight, this.form.ignore, jsonList,this.form.generate).then((res) => {
        // console.log('返回成功，结果：', res)
        if (res.status === '1') {
          this.submitSuccessNotify('插队任务成功')
          this.submitstatus =  true
        } else {
          this.submitFailureNotify('插队任务失败','')
          this.submitstatus =  true
          // console.log('11111111', this.dataArr)
        }
        }).catch((error) => {
          this.submitFailureNotify('fileSel与后端通讯发生错误', error)
          this.submitstatus =  true
        })
      }

    },
  }
}

</script>
<style scoped>
.leftDiv{
  text-align: left;
  padding-bottom:2mm;
  padding-right: 2mm;
  padding-top: 2mm;
}
.explorerBox {
  height: 500px;
  overflow: auto;
}
.text_class{
  text-align:center;
  margin: auto;
  font-size: 20px;
  position: relative;
}
.btn1Class {
  font-size: 16px;
  margin-right: 30px;
  margin-left: 5px;
}
.btn2Class {
  font-size: 16px;
  margin-right: 20px;
  margin-left: 15px;
}
.btn3Class{
  font-size: 5px;
  padding-left: 12px;
  padding-top: 9px;
  padding-bottom: 9px;
  padding-right: 12px;

  margin-top: 5px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
